﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Serilog;
using Ls.Utils;
using Ls.Web.Framework.Extensions;
using Ls.Web.Framework.Permissions;
using Ls.Web.Api.Models;
using Ls.Web.Framework.Jwt;
using Swashbuckle.AspNetCore.Swagger;
using Microsoft.Extensions.PlatformAbstractions;
using System.IO;
using Ls.Web.Api.Infrastructure;

namespace Ls.Web.Api
{
    public class Startup
    {
       
        public Startup(IHostingEnvironment hostingEnvironment)
        {
            _env = hostingEnvironment;
            Configuration = new ConfigurationBuilder()
               .SetBasePath(hostingEnvironment.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .Build();
            Log.Logger = new LoggerConfiguration()
              .ReadFrom.Configuration(Configuration)
              .CreateLogger();
        }

        public IConfiguration Configuration { get; }
        private readonly IHostingEnvironment _env;
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));
            services.TryAddScoped<IHttpContextAccessor, HttpContextAccessor>();
            services.Configure<JwtSecurityTokenOptions>(Configuration.GetSection("IdentityOptions:JwtSecurityToken"));
            // Metrics监控配置
            services.AddMetrics(Configuration);
            services.AddMvc();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "新模式App 接口文档", Version = "v1" });
                c.IncludeXmlComments(Path.Combine(PlatformServices.Default.Application.ApplicationBasePath,
                    "Ls.Web.Api.xml"));
                c.DescribeAllEnumsAsStrings();
                c.OperationFilter<HttpHeaderFilter>();
            });
            // Make IOptions<ExceptionalSettings> available for injection everywhere
            services.AddExceptional(Configuration.GetSection("Exceptional"), settings =>
            {
                settings.UseExceptionalPageOnThrow = _env.IsDevelopment();
            });

            services.TryAddScoped<IPermissionService, MenuService>();
            services.AddSxAuthentication();
            services.AddCache();
            var jwtOptions = new JwtSecurityTokenOptions();
            Configuration.GetSection("IdentityOptions:JwtSecurityToken").Bind(jwtOptions);
            services.ConfigureJwtAuthentication(jwtOptions, _env);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider svp)
        {
            SxHttpContext.ServiceProvider = svp;
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseSxAuthentication();
            app.UseJwtTokenMiddleware();

            // 注入Metrics
            app.UseMetrics(Configuration); 
            // 路由
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(
                  name: "areas",
                  template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
                );
            });
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });
            app.UseExceptional();
        }
    }
}
